#/bin/bash -e

source cluster_ip.conf

function restart_ceph() {
    i=0
    for node in $CEPH1 $CEPH2 $CEPH3 $CEPH4
    do
        ssh $node "
            cd \$HOME/ceph-demo/build
            ../src/stop.sh
            rm -rf out dev
            RGW=1 ../src/vstart.sh -c $i --smallmds --new -X --localhost --msgr1 --without-dashboard --fabric_kafka_brokers \
            ${FABRIC}:$KAFKA_PORT --fabric_kafka_topic $KAFKA_TOPIC --fabric_sdk_addr ${FABRIC}:8080 > \$HOME/ceph-demo/build/start.log 2>&1
        " &
        let i=i+1
    done
    wait
}

function test_ceph_run() {
    for node in $CEPH1 $CEPH2 $CEPH3 $CEPH4
    do
        ssh $node "
            ceph_status=\$(timeout 2s ceph health)
            if [ 0\$ceph_status == '0' ]; then
                exit -1
            fi
        "
        if [ $? -ne 0 ]; then
            echo "No ceph running in [$node], stop gen data"
            exit -1
        fi
    done
}

function gen_rados_objs() {
    for node in $CEPH1 $CEPH2 $CEPH3 $CEPH4
    do
        ssh $node "
            ceph osd pool create testbench 32 32
            ceph osd pool application enable testbench rgw
        " &
    done
    wait
    for node in $CEPH1 $CEPH2 $CEPH3 $CEPH4
    do
        ssh $node "
            rados --put-hash-to-fabric bench -p testbench 20 write -t 32 --no-cleanup >> \$HOME/ceph-demo/build/start.log
        " &
    done
    wait
}

function redeploy_fabric() {
    ssh $FABRIC "
        source /etc/profile
        fabric_sdk=\$(ps -ef | grep benchmark | grep -v grep | awk '{print \$2}')
        for id in \$fabric_sdk
        do
            sudo kill -9 \$id
        done
        cd \$HOME/ceph_fabric_config/kafka
        git pull
        ./start.sh -i $FABRIC
        cd \$HOME/ceph_fabric_config/fabric_install_deploy/
        ./deploy_fabric.sh
        cd \$HOME/go/src/fabric-sdk/
        git pull
        nohup go run benchmark.go > \$HOME/fabric_sdk.log 2>&1 &
    "
}

redeploy_fabric

restart_ceph

test_ceph_run

gen_rados_objs

